package com.scs.application.modules.base.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.Location;
import com.scs.application.modules.base.entity.Warehouse;
import com.scs.application.modules.base.service.LocationService;
import com.scs.application.modules.base.service.WarehouseService;
import com.scs.application.modules.report.handler.BeforeReport;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.wm.entity.Stock;
import com.scs.application.modules.wm.service.StockService;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 */
@RestController
@RequestMapping("/base/location")
public class LocationController extends CrudController<LocationService, Location>{
    @Autowired
    StockService stockService;
    @Autowired
    WarehouseService warehouseService;

    @RequestMapping("/getByCode")
    public RestResult getDistByKey(@RequestParam String warehouseId, @RequestParam String locationCode ) {
        Location location = service.getOne(Wrappers.<Location>query()
                .eq("warehouse_id", warehouseId)
                .eq("code", locationCode));
        return location == null ? RestResult.error("未找到货位") : RestResult.ok("查询成功！", location);
    }

    /**
     * 删除数据
     */
    @DeleteMapping("/delete")
    public RestResult deleteItems(@RequestBody Map<String, Object> para) {
        List<Serializable> ids = (List<Serializable>) para.get("ids");
        if(stockService.count(Wrappers.<Stock>query().in("location_id",ids)) > 0) throw new BusinessException("该库位已有库存记录，不允许删除");
        if(service.count(Wrappers.<Location>query().in("parent_id",ids)) > 0) throw new BusinessException("该库位有下级库位，不允许删除");
        Boolean isOk = service.removeCascadeByIds(ids);
        if (!isOk) {
            return RestResult.error("数据删除失败");
        }
        return RestResult.ok("数据删除成功");
    }


    /**
     * 选择 获取数据列表
     */
    @GetMapping("/pageForSelect")
    public PageResult pageForSelect(@RequestParam Map<String, Object> reqData) {
        QueryContext queryContext = QueryContextHolder.currentContext();
        Map<String, Object> userParam =null;
        //固定参数
        if(reqData.containsKey("userParam")){
            JSONObject ob = JSON.parseObject(reqData.get("userParam")+"");
            userParam= Maps.newHashMap(ob);
        }

        //根据用户所有工位权限，筛选工位列表
        if (!BeforeReport.getFlagAllData()) {
            List<String> userWarehouseIdList = BeforeReport.getUserWarehouseIdList();
            if(userWarehouseIdList != null) {
                queryContext.getWrapper().in("id", BeforeReport.getUserWarehouseIdList());
            }else {
                queryContext.getWrapper().eq("1",0);
            }
        }


        IPage pageResult = service.pageForSelect(queryContext,userParam);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }

    /**
     * 智能柜选择 获取数据列表
     */
    @GetMapping("/pageFsdForSelect")
    public PageResult pageFsdForSelect(@RequestParam Map<String, Object> reqData) {
        QueryContext queryContext = QueryContextHolder.currentContext();
        Map<String, Object> userParam =null;
        //固定参数
        if(reqData.containsKey("userParam")){
            JSONObject ob = JSON.parseObject(reqData.get("userParam")+"");
            userParam= Maps.newHashMap(ob);
        }

        //根据用户所有工位权限，筛选工位列表
        if (!BeforeReport.getFlagAllData()) {
            List<String> userWarehouseIdList = BeforeReport.getUserWarehouseIdList();
            if(userWarehouseIdList != null) {
                queryContext.getWrapper().in("warehouse_id", BeforeReport.getUserWarehouseIdList());
            }else {
                queryContext.getWrapper().eq("1",0);
            }
        }

        queryContext.getWrapper().eq("type","fsd");
        queryContext.getWrapper().isNotNull("type");

        IPage pageResult = service.pageForSelect(queryContext,userParam);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }

    /**
     * 根据ID查找数据
     */
    @GetMapping("/find")
    @Override
    public RestResult find(@RequestParam("id") Serializable id) {
        Location entity = service.getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        if (StringUtils.isNotBlank(entity.getParentId())) {
            Location entityFind = service.getOne(Wrappers.<Location>query().eq("id",entity.getParentId()), false);
            if (entityFind != null) {
                entity.setParentName(entityFind.getName());
            }
        }
        if (StringUtils.isNotBlank(entity.getWarehouseId())) {
            Warehouse entityFind = warehouseService.getById(entity.getWarehouseId());
            if (entityFind != null) {
                entity.setWarehouseName(entityFind.getName());
            }
        }
        return RestResult.ok("获取数据成功", entity);
    }
}
